package com.dev.utils.app.assist;

import com.dev.utils.LogUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.window.dialog.ToastDialog;
import ohos.sensor.agent.CategoryOrientationAgent;
import ohos.sensor.bean.CategoryOrientation;
import ohos.sensor.data.CategoryOrientationData;
import ohos.sensor.listener.ICategoryOrientationDataCallback;

/**
 * 屏幕旋转监听工具类，使用重力传感器
 */
public class ScreenSensorAssist {

    //重力传感器相关
    private static final long INTERVAL = 100000000L;
    private static CategoryOrientationAgent categoryOrientationAgent = new CategoryOrientationAgent();
    private static ICategoryOrientationDataCallback orientationDataCallback;
    private static CategoryOrientation orientationSensor;
    private static int matrix_length = 9;
    private static int rotationVectorLength = 9;

    /**
     * 创建传感器回调对象
     *
     * @param slice
     */
    public static void initOritation(AbilitySlice slice) {
        // 创建传感器回调对象
        orientationDataCallback = new ICategoryOrientationDataCallback() {
            @Override
            public void onSensorDataModified(CategoryOrientationData categoryOrientationData) {
                // 对接收的categoryOrientationData传感器数据对象解析和使用
                int dim = categoryOrientationData.getSensorDataDim(); // 获取传感器的维度信息
                float degree = categoryOrientationData.getValues()[0]; // 获取方向类传感器的第一维数据
                float[] rotationMatrix = new float[matrix_length];
                CategoryOrientationData.getDeviceRotationMatrix(rotationMatrix, categoryOrientationData.values); // 根据旋转矢量传感器的数据获得旋转矩阵
                float[] rotationAngle = new float[rotationVectorLength];
                rotationAngle = CategoryOrientationData.getDeviceOrientation(rotationMatrix, rotationAngle); // 根据计算出来的旋转矩阵获取设备的方向
            }

            @Override
            public void onAccuracyDataModified(CategoryOrientation categoryOrientation, int index) {
                // 使用变化的精度
            }

            @Override
            public void onCommandCompleted(CategoryOrientation categoryOrientation) {
                // 传感器执行命令回调
                new ToastDialog(slice).setText("屏幕旋转").show();
                LogUtils.info("Oritation", "屏幕发生旋转！");
            }
        };
    }

    /**
     * 获取传感器对象，并订阅传感器数据
     */
    public static void subscribeOritation() {
        orientationSensor = categoryOrientationAgent.getSingleSensor(
                CategoryOrientation.SENSOR_TYPE_SCREEN_ROTATION);
        if (orientationSensor != null) {
            categoryOrientationAgent.setSensorDataCallback(
                    orientationDataCallback, orientationSensor, INTERVAL);
        }
    }

    /**
     * 取消订阅传感器数据
     */
    public static void unSubscribeOritation() {
        if (orientationSensor != null) {
            categoryOrientationAgent.releaseSensorDataCallback(
                    orientationDataCallback, orientationSensor);
        }
    }
}
